<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="模具类型">
          <el-tree-select
            v-model="searchParam.assetTypeId"
            node-key="id"
            :check-strictly="true"
            :props="{
              children: 'nodes',
              label: 'assetTypeName',
            }"
            placeholder="请选择模具类型"
            :data="deviceList"
            filterable
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="客户">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请选择客户"
            clearable
            filterable
          >
            <el-option
              v-for="item in customerList"
              :key="`${item.id}`"
              :label="`${item.partnerName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品">
          <el-select
            v-model="searchParam.productId"
            placeholder="请选择产品"
            clearable
            filterable
            :filter-method="productCustomFilter"
          >
            <el-option
              v-for="item in productFilteredOptions"
              :key="`${item.id}`"
              :label="`${item.materialName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模具状态">
          <el-select
            v-model="searchParam.queryStatus"
            placeholder="请选择模具状态"
            clearable
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList(
                'moldStatisticsType'
              )"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="位置">
          <el-tree-select
            placeholder="请选择位置"
            filterable
            v-model="searchParam.locationId"
            :data="locationInfoTree"
            node-key="id"
            clearable
            :props="{ label: 'locationName', children: 'nodes' }"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="模具名称">
          <el-input
            clearable
            v-model="searchParam.assetName"
            placeholder="请输入模具名称"
          />
        </el-form-item>
        <el-form-item label="模具选择">
          <el-select
            v-model="searchParam.assetCode"
            placeholder="请选择模具"
            clearable
            filterable
            :filter-method="mouldCustomFilter"
          >
            <el-option
              v-for="item in mouldFilteredOptions"
              :key="`${item.assetCode}`"
              :label="`${item.assetName}`"
              :value="`${item.assetCode}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="handleReset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div style="display: flex; justify-content: space-between">
          <div></div>
          <div v-if="searchParam.queryStatus == '2'">
            <!-- <el-form :model="searchParam" :inline="true">
              <el-form-item label="仓库">
                <el-input
                  v-model="searchParam.makerName"
                  placeholder="请选择仓库"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
              <el-form-item label="存储区域">
                <el-input
                  v-model="searchParam.makerName"
                  placeholder="请选择存储区域"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
            </el-form> -->

            <!-- <el-button
              size="large"
              style="background-color: #81b337; color: black"
              >生 产</el-button
            > -->
            <el-button
              size="large"
              style="background-color: #81b337; color: black"
              @click="hangdleClick(3)"
              >正 常</el-button
            >
            <el-button
              size="large"
              style="background-color: #0066ff; color: black"
              @click="hangdleClick(6)"
              >开 发</el-button
            >
            <el-button
              size="large"
              style="background-color: #d40000; color: black"
              @click="hangdleClick(2)"
              >维 修</el-button
            >
            <el-button
              size="large"
              style="background-color: #fff81d; color: black"
              @click="hangdleClick(1)"
              >生 产</el-button
            >
          </div>
        </div>
      </template>

      <!-- <div class="content">
        <div v-for="(item, index) in tableData" :key="item.id">
          <div class="box" :style="{ background: item.color }">
            <div style="margin-top: 5px; font-weight: 700">
              {{ item.locationName }}
            </div>
            <div style="margin: 5px 0">{{ item.assetName }}</div>
            <div v-if="item.process">
              使用进度<span style="font-weight: 700">{{ item.process }}</span>
            </div>
          </div>
        </div>
      </div> -->
      <div class="content">
        <div v-for="(item, index) in tableData" :key="item.id">
          <div
            @click="openDialogdetail(item)"
            class="box"
            :style="{
              background:
                item.assetStatus == 3
                  ? '#81b337'
                  : item.assetStatus == 1
                  ? '#fff81d'
                  : item.assetStatus == 2
                  ? '#d40000'
                  : item.assetStatus == 6
                  ? '#0066ff'
                  : '',
            }"
          >
            <div class="box1">
              <span> {{ item.locationName || "" }}</span>
              <span>
                {{
                  dictionaryStore.filterDictName(
                    "MouldStatus",
                    item.assetStatus
                  ) || ""
                }}</span
              >
            </div>
            <div class="box1">
              <span>{{ item.assetName || "" }}</span>
              <span>{{ item.productName || "" }}</span>
            </div>
            <div class="box2">
              <span
                >累计模数:<span class="test">{{
                  item.cumulativeUseTimes || ""
                }}</span></span
              >
              <span
                >模具寿命:<span class="test">{{
                  item.assetLifespan || ""
                }}</span>
              </span>
            </div>
            <div>
              使用进度:<span class="test"
                >{{
                  getPercentage(item.assetLifespan, item.cumulativeUseTimes)
                }}%</span
              >
            </div>
          </div>
        </div>
      </div>
      <div
        v-if="tableData.length == 0"
        style="text-align: center; color: #909399; font-size: 14px"
      >
        暂无数据
      </div>
      <!-- moldStatisticsType -->
      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <molddeviceinfo-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :assetTypeIdTree="assetTypeIdTree"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionar } from "@/utils/useTable";
import request from "@/utils/request";
import _ from "lodash-es";
import { filterOrder } from "@/utils/commonHooks";
import { getStandardDevicesApi } from "@/utils/commonData";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "EAMMOLDMOLDSTATISTICS",
  inheritAttrs: false,
});
const props = defineProps({
  assetKind: {
    type: Number,
    default: null,
  },
});

const { assetKind } = toRefs(props);

// 请求参数
const requestApi = "/eam/mouldAssetInfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetTypeId: "",
  projectId: "",
  productId: "",
  queryStatus: "2",
  locationId: "",
  assetCode: "",
  assetStatus: "",
  assetKind: 3,
};

const deleteParam = {
  api: "/eam/eammaker/delete",
  data: { assetKind: assetKind.value },
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行
const pageSize = ref(1);
const pageNum = ref(50);
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam,
  pageSize,
  pageNum
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

const getPercentage = (assetLifespan: number, cumulativeUseTimes: number) => {
  if (!assetLifespan || !cumulativeUseTimes) return 0;
  return Number((cumulativeUseTimes / assetLifespan) * 100).toFixed(2);
};

// 获取客户
const customerList: any = ref([]);
const getCustomerList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmpartner/getPoList",
    method: "POST",
    data: {},
  }).then((res) => {
    customerList.value = res.data;
  });
};
// 获取项目
const productList: any = ref([]);
const getProductList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmmaterial/getList",
    method: "POST",
    data: { materialType: "3" },
  }).then((res) => {
    productList.value = res.data;
    productFilteredOptions.value = res.data;
  });
};

const productFilteredOptions = ref([]);

// 使用 debounce 包装过滤方法
const productCustomFilter = _.debounce((query: any) => {
  if (!query) {
    productFilteredOptions.value = [...productList.value];
    return;
  }
  productFilteredOptions.value = productList.value.filter((option: any) =>
    option.materialName.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

const mouldList: any = ref([]);
const getMouldList = async () => {
  // 获取内容树
  await request({
    url: "/eam/mouldAssetInfo/getList",
    method: "POST",
    data: {},
  }).then((res) => {
    mouldList.value = res.data;
    mouldFilteredOptions.value = res.data;
  });
};
const mouldFilteredOptions = ref([]);
// 使用 debounce 包装过滤方法
const mouldCustomFilter = _.debounce((query: any) => {
  if (!query) {
    mouldFilteredOptions.value = [...mouldList.value];
    return;
  }
  mouldFilteredOptions.value = mouldList.value.filter((option: any) =>
    option.assetName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);
// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

const handleSearch = () => {
  searchParam.value.assetStatus = "";
  search();
};
const handleReset = () => {
  searchParam.value.assetStatus = "";
  reset();
};

const hangdleClick = (assetStatus) => {
  if (assetStatus == 3) {
    searchParam.value.assetStatus = assetStatus;
    search();
  } else if (assetStatus == 2) {
    searchParam.value.assetStatus = assetStatus;
    search();
  } else if (assetStatus == 6) {
    searchParam.value.assetStatus = assetStatus;
    search();
  } else if (assetStatus == 1) {
    searchParam.value.assetStatus = assetStatus;
    search();
  }
};

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/mouldAssetInfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产台账表单弹窗 */
const assetTypeIdTree = ref("");

/** 打开资产台账表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "模具详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    assetTypeIdTree.value = "";
  }
}

const deviceList = ref(<any>[]);
async function getDeviceList() {
  const params = {
    assetKind: 3,
  };
  deviceList.value = (await getStandardDevicesApi(params)) ?? [];
}
onMounted(() => {
  getTableList();
  getDeviceList();
  getMouldList();
  getProductList();
  getCustomerList();
  getLocationInfoTree();
});
</script>
<style scoped lang="scss">
.box {
  width: 270px;
  height: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
  margin: 0 10px 10px 0;
  border: 1px solid #d4d4d4;
  border-radius: 10px;
  padding: 0 10px;
  .box1 {
    margin-top: 5px;
    font-weight: 700;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .box2 {
    display: flex;
    width: 100%;
    justify-content: center;
    align-items: center;
    margin-top: 5px;
  }
}
.test {
  font-weight: 700;
  margin: 0 5px 0 5px;
}
.content {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
  cursor: pointer;
}
</style>
